import { defineStore } from 'pinia'
import { userInfoApi } from '~/api/user'
import type { UserInfo } from '~/api/model/user'

export const useUserStore = defineStore(
    'user',
    () => {
        // 用户信息状态
        const user = ref<UserInfo>({
            username: '',
            curVip: 0,
            id: 0,
            uid: 0,
            targetProgress: 0,
        })
        const isLogin = computed(() => {
            return Boolean(user.value && user.value.uid)
        })
        // 初始化用户信息
        function setUser(userInfo: UserInfo) {
            user.value = userInfo
        }

        // 清除用户信息
        function clearUser() {
            user.value = {
                username: '默认用户',
                curVip: 0,
                id: 0,
                avatar: '/imgs/head1.png',
                uid: 0,
                targetProgress: 0,
            }

        }

        // 从 API 获取用户信息
        async function getUserInfo() {
            try {
                const res = await userInfoApi()
                if (res.code==0) {
                    // console.log('获取用户信息:', res)
                    setUser(res.data)
                    // isLogin.value=true
                } else {
                    // isLogin.value=false
                    clearUser()
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                clearUser()
                // isLogin.value=false
            }
        }

        return {
            user,
            isLogin,
            setUser,
            clearUser,
            getUserInfo,
        }
    },
    {
        persist: true, // 关键配置：启用持久化
    }
)